<template>
  <van-popup v-model:show="showPopup" position="right" destroy-on-close :style="{ width: '100%', height: '100%' }" teleport="body">
    <van-nav-bar :title="operation === 'add' ? '新增客户' : '编辑客户'" fixed @click-right="showPopup = false">
      <template #right>
        <van-icon name="cross" size="18" />
      </template>
    </van-nav-bar>
    <div class="form-wrapper">
      <van-form @submit="onSubmit">
        <van-cell-group>
          <van-field v-model="form.nickName" label="姓名" placeholder="请输入姓名" :rules="[{ required: true, message: '请输入姓名' }]" />
          <van-field
            v-model="form.mobile"
            label="手机号"
            placeholder="请输入手机号"
            :rules="[
              { required: true, message: '请输入手机号' },
              { validator: validateMobile, message: '请输入正确的手机号' }
            ]"
          />
          <van-field label="状态">
            <template #input>
              <van-radio-group v-model="form.state" direction="horizontal">
                <van-radio :name="1">正常</van-radio>
                <van-radio :name="0">禁用</van-radio>
              </van-radio-group>
            </template>
          </van-field>
        </van-cell-group>
        <div class="btn-wrapper">
          <van-button class="btn-item" block type="default" @click="showPopup = false"> 取消 </van-button>
          <van-button class="btn-item" block type="primary" native-type="submit"> 保存 </van-button>
        </div>
      </van-form>
    </div>
  </van-popup>
</template>

<script setup>
import { ref } from 'vue'
import { apiCreateCustomer, apiUpdateCustomer } from '@/api/customer'
import { showToast } from 'vant'
import { validateMobile } from '@/utils/validate'

const emit = defineEmits(['refresh'])

const showPopup = ref(false)
const form = ref({})
const operation = ref('add')

const open = (customer, type) => {
  form.value = customer
  operation.value = type
  showPopup.value = true
}

const onSubmit = () => {
  let result
  if (operation.value === 'add') {
    result = apiCreateCustomer(form.value)
  } else {
    result = apiUpdateCustomer(form.value)
  }
  result.then((res) => {
    showToast({
      message: '保存成功',
      position: 'top'
    })
    showPopup.value = false
    emit('refresh')
  })
}

defineExpose({
  open
})
</script>

<style lang="less" scoped>
.form-wrapper {
  padding-top: var(--van-nav-bar-height);
  .btn-wrapper {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    .btn-item {
      width: 47%;
    }
  }
}
</style>
